#include <iostream>
#include <sstream>
#include <string>
#include <jsoncpp/json/json.h>
#include <memory>
using namespace std;

//序列化
bool serialize(const Json::Value val,string& out)
{
    //创建工厂
    Json::StreamWriterBuilder factory;
    factory["emitUTF8"] = true;
    stringstream ss;
    //工厂创建对象
    unique_ptr<Json::StreamWriter> sw(factory.newStreamWriter());
    int r = sw->write(val,&ss);    
    if(r != 0)
    {
        cout << "Json serialize fail!!!" << endl;
        return false;
    }
    out = ss.str();
    return true;
}

//反序列化
bool unserialize(const string in,Json::Value& val)
{
    //创建工厂
    Json::CharReaderBuilder factory;
    
    //工厂创建对象
    unique_ptr<Json::CharReader> cr(factory.newCharReader());

    string errs;
    int r = cr->parse(in.c_str(),in.c_str()+in.size(),&val,&errs);
    if(r == false)
    {
        cout << "Json unserialize fail!!!" <<endl;
        return false;
    }
    return true;

}

int main()
{
    //原始数据
    const char* name = "小明";
    int age = 18;
    const char* sex = "男";
    float socre[] = {77,88.5,99};
    //中间数据存储
    Json::Value student;

    Json::Value fav;
    fav["爱好"] = "健身";
    fav["爱好"] = "唱歌";


    student["姓名"] = name;
    student["年龄"] = age;
    student["性别"] = sex;
    student["成绩"].append(socre[0]);
    student["成绩"].append(socre[1]);
    student["成绩"].append(socre[2]);
    //嵌套
    student["爱好"] = fav;

    string s;
    serialize(student,s);
    //打印上面序列化出来的东西
    cout << s << endl;

    cout << "————————————————————" <<endl;

    string r = R"({"姓名":"小花","年龄":18,"性别":"女"})";

    Json::Value stu;
    unserialize(r,stu);

    string names = stu["姓名"].asString();
    int ages = stu["年龄"].asInt();
    string sexs = stu["性别"].asString();
    cout << "names: " << names << endl;
    cout << "ages: " << ages << endl;
    cout << "sexs: " << sexs << endl;


    return 0;
}